/*
Copyright 2009 David Revell

This file is part of SwiFTP.

SwiFTP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

SwiFTP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with SwiFTP.  If not, see <http://www.gnu.org/licenses/>.
*/

package lfr.ustc.ftp;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class DataSocket {

	ServerSocket server = null;
	InetAddress remoteAddr;
	int remotePort;
	boolean isPasvMode = true;

	public DataSocket() {
		clearState();
	}

	private void clearState() {
		if (server != null) {
			try {
				server.close();
			} catch (IOException e) {
			}
		}
		server = null;
		remoteAddr = null;
		remotePort = 0;
	}

	public boolean onPort(InetAddress remoteAddr, int remotePort) {
		clearState();
		this.remoteAddr = remoteAddr;
		this.remotePort = remotePort;
		return true;
	}

	public int onPasv() {
		try {
			server = new ServerSocket(0, 3);
			return server.getLocalPort();
		} catch (IOException e) {
			clearState();
			return 0;
		}
	}

	public Socket onTransfer() {
		if (server == null) {
			if (remoteAddr == null || remotePort == 0) {
				clearState();
				return null;
			}
			Socket socket;
			try {
				socket = new Socket(remoteAddr, remotePort);
			} catch (IOException e) {
				clearState();
				return null;
			}

			try {
				socket.setSoTimeout(5000);
			} catch (Exception e) {
				clearState();
				return null;
			}

			return socket;
		} else {
			Socket socket = null;
			try {
				socket = server.accept();
			} catch (Exception e) {
				socket = null;
			}
			clearState();
			return socket;
		}
	}
}